<?php 
// +----------------------------------------------------------------------
// | CRMUU-企微SCRM是专业的企业微信第三方源码系统.
// +----------------------------------------------------------------------
// | [CRMUU] Copyright (c) 2022 http://crmuu.com All rights reserved.
// +----------------------------------------------------------------------

namespace app\wework\controller\h5;

use app\wework\controller\Base;
use app\BaseController;
use think\facade\Db;
use app\wework\model\QyWechatApi;
use app\wework\model\Helper;
use app\wework\model\user\autogroup\AutoPullGroupModel;
use think\facade\Log;

use think\facade\View;
/**
  * 自动拉群  h5端
*/
class AutoPullGroup extends Base
{
	public function index(){
		$id = $this->req->param("id");
		if(!$id)return "参数错误";
		$auto = Db::table("kt_wework_group_auto")->where(["id"=>$id])->json(["staffs"])->find();
		$code = $this->req->param("code");
		$wid = $auto["wid"];
		$config = Helper::getConfig($wid);
		$selfapp = Helper::getSelfapp($wid);
		if($code){
			$resArr = QyWechatApi::getuserinfo($wid,$code);
			$auto_data = Db::table("kt_wework_group_auto_data")->where(["wid"=>$wid,"pid"=>$id,"status"=>1])->find();
			if(!$auto_data)return "该拉群活码已结束";
			$group = Db::table("kt_wework_group")->where(["wid"=>$wid,"id"=>$auto_data["group_id"]])->find();
			$count = Db::table("kt_wework_group_member")->where(["wid"=>$wid,"chat_id"=>$group["chat_id"],"status"=>1])->count();
			if($auto_data["size"] <= $count){
				$orders = $auto_data["orders"]+1;
	    		Db::table("kt_wework_group_auto_data")->where(["wid"=>$wid,"group_id"=>$group["id"],"status"=>1])->update(["status"=>3]);
	    		$next = Db::table("kt_wework_group_auto_data")->where(["wid"=>$wid,"pid"=>$id,"status"=>2,"orders"=>$orders])->find();
	    		if($next)Db::table("kt_wework_group_auto_data")->where(["wid"=>$wid,"pid"=>$id,"status"=>2,"orders"=>$orders])->update(["status"=>1]);
	    		$auto_data = Db::table("kt_wework_group_auto_data")->where(["wid"=>$wid,"pid"=>$id,"status"=>2,"orders"=>$orders])->find();
	    		if(!$next) return "该拉群活码已结束";
	    	}
	    	if(isset($resArr["external_userid"]) && $auto["join_type"] == 2){
	    	    $is_set = Db::table("kt_wework_customer")->where(["status"=>0,"external_userid"=>$resArr["external_userid"],"staff_id"=>$auto["staffs"]])->find();
	    	    $is_set = 0;
	    	    if(!$is_set)$auto_data["code"] = $auto["standby_status"]?$auto["standby_qrcode"]:$auto["qr_code"];
	    	}
	    }else{
	    	$redirect_uri = urlencode($this->req->domain().'/wework/h5.AutoPullGroup/index.html?id='.$id);
			$url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$config["corp_id"].'&redirect_uri='.$redirect_uri.'&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect';
			return redirect($url);
	    }
	    
		View::assign("auto", $auto);
		View::assign("auto_data", $auto_data);
		return view();
	}
}